package com.rm.zeyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rm.zeyou.constant.NumberConstants;
import com.rm.zeyou.entity.BrokerApply;
import com.rm.zeyou.entity.Technician;
import com.rm.zeyou.exception.ErrorCodeException;
import com.rm.zeyou.exception.ErrorCodeExceptionEnum;
import com.rm.zeyou.mapper.BrokerApplyMapper;
import com.rm.zeyou.mapper.BrokerMapper;
import com.rm.zeyou.mapper.TechnicianMapper;
import com.rm.zeyou.response.ApiRestResponse;
import com.rm.zeyou.service.BrokerApplyService;
import com.rm.zeyou.util.check.CheckEmptyUtil;
import com.rm.zeyou.vo.request.ApplyBrokerVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author YanYang
 * @since 2025-03-25 10:58:33
 */
@Service
public class BrokerApplyServiceImpl extends ServiceImpl<BrokerApplyMapper, BrokerApply> implements BrokerApplyService {
    @Resource
    private BrokerApplyMapper brokerApplyMapper;
    @Resource
    private TechnicianMapper technicianMapper;
    @Resource
    private BrokerMapper brokerMapper;

    @Override
    public ApiRestResponse<Integer> applyBroker(Technician technician, ApplyBrokerVo applyVo) {
        //判断是否有正在审核或审核成功的数据
        int successCount = brokerApplyMapper.selectCount(new LambdaQueryWrapper<BrokerApply>()
                .eq(BrokerApply::getTid, technician.getId())
                .ne(BrokerApply::getAuditStatus, NumberConstants.TWO_CONSTANTS)).intValue();
        if (successCount > 0) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.AUDITING);
        }


        //如果填写上级手机号
        //已有上级  报错
        //没有上级  查询填的上级手机号是否正确  //正确 存表  错误报错
        if (!CheckEmptyUtil.isEmpty(applyVo.getPartnerTel())) {

            if (!CheckEmptyUtil.isEmpty(technician.getTechnicianInvitedCode())) {
                throw new ErrorCodeException(ErrorCodeExceptionEnum.IS_BIND_PARTNER);
            }
            Technician partnerTechnician = technicianMapper.selectOne(new LambdaQueryWrapper<Technician>()
                    .eq(Technician::getTechnicianTel, applyVo.getPartnerTel()));
            if (CheckEmptyUtil.isEmpty(partnerTechnician)) {
                throw new ErrorCodeException(ErrorCodeExceptionEnum.PARTNER_EMPTY);
            }

        }
        BrokerApply brokerApply = new BrokerApply();
        brokerApply.setUserId(technician.getUserId());
        brokerApply.setTid(technician.getId());
        brokerApply.setName(applyVo.getName());
        brokerApply.setTel(applyVo.getTel());
        brokerApply.setPartnerTel(applyVo.getPartnerTel());
        brokerApply.setChannelName(applyVo.getChannelName());
        brokerApply.setRemark(applyVo.getRemark());
        int insert = brokerApplyMapper.insert(brokerApply);
        return ApiRestResponse.success(insert);
    }


}
